<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\controller\admin;

use app\book\base\BookAdminBase;

use app\book\model\Book;
use app\book\model\Chapter as ChapterModel;
use app\book\model\ChapterData;

class Chapter extends BookAdminBase{
    //当前控制器菜单
    public $submenu = [];
    // 图书信息
    private $book;
    /**
     * TP初始化方法
     */
    public function _initialize() {
        parent::_initialize();
        // 获取图书信息
        $book_id = $this->request->param('book_id/d');
        if(!$book_id){
            $this->error('缺少图书id');
        }
        // 查询图书信息
        $this->book = Book::get($book_id);
        if(!$this->book){
            $this->error('图书不存在');
        }

        $this->submenu[] = ['title' => '图书列表', 'url' => url('book/admin.index/index'), 'icon' => '&#xe60a;'];
        $this->submenu[] = ['title' => '章节列表', 'url' => url('book/admin.chapter/index',['book_id' => $this->book->id]), 'icon' => '&#xe60a;'];
        $this->submenu[] = ['title' => '添加章节', 'url' => url('book/admin.chapter/add',['book_id' => $this->book->id]), 'icon' => '&#xe654;'];
    }

    /**
     * 章节列表
     * @access public
     * @return \think\Response
     */
    public function index(){
        $chapter_list = ChapterModel::where('book_id',$this->book->id)->order('displayorder desc')->paginate(config('mn_admin.admin_pagesize'));
        $this->assign([
            'submenu'   => $this->submenu,
            'list'      => $chapter_list,
            'book'      => $this->book
        ]);
    	return $this->fetch();
    }

    /**
     * 章节添加
     * @access public
     * @param ChapterModel $chapter
     * @return \think\Response
     */
    public function add(ChapterModel $chapter){
        // POST提交数据
        if($this->request->isPost()){
            // 获取提交的数据
            $post_data = $this->buildParam();
                // 验证主表字段
            $validate_result = $this->validate($post_data,'Chapter');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'ChapterData');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 生成排序值
            $post_data['displayorder'] = ChapterModel::where('book_id', $this->book->id)->max('displayorder') + 1;
            // 启用事务
            $chapter->startTrans();
            try{
                if($chapter->allowField(true)->save($post_data)){
                    $chapter_data = new ChapterData;
                    $chapter_data->content = $post_data['content'];
                    $chapter->chapterData()->save($chapter_data);
                }
                $chapter->commit();
            } catch (\Exception $e) {
                // 回滚事务
                $chapter->rollback();
                $this->error($e->getFile().':'.$e->getLine().':'.$e->getMessage(),null,'',100);
            }
            $this->success('操作成功', url('index', ['book_id' => $chapter->book_id]));
        }

        // 降序排序分卷
        if(is_array($this->book->volumes)){
            $volumes = $this->book->volumes;
            krsort($volumes);
            $this->book->volumes = $volumes;
        }

        $this->assign([
            'submenu'   => $this->submenu,
            'book'      => $this->book
        ]);
        return $this->fetch();
    }

    /**
     * 章节修改
     * @access public
     * @return \think\Response
     */
    public function edit($id = 0){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少章节ID');
        }
        $chapter = ChapterModel::relation('chapter_data')->find($id);
        if(!$chapter){
            $this->error('章节不存在');
        }
        // POST提交数据
        if($this->request->isPost()){
            $post_data = $this->buildParam();
            // 验证主表字段
            $validate_result = $this->validate($post_data,'Chapter');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'ChapterData');
            if(true !== $validate_result){
                // 验证失败 输出错误信息
                $this->error($validate_result);
            }
            // 启用事务
            $chapter->startTrans();
            try{
                if($chapter->allowField(true)->save($post_data,['id' => $chapter->id])){
                    $chapter->chapter_data->content = $post_data['content'];
                    $chapter->chapter_data->save();
                }
                $chapter->commit();
            } catch (\Exception $e) {
                // 回滚事务
                $chapter->rollback();
                $this->error($e->getFile().':'.$e->getLine().':'.$e->getMessage(),null,'',100);
            }
            $this->success('操作成功', url('index', ['book_id' => $chapter->book_id]));
        }

        // 降序排序分卷
        if(is_array($this->book->volumes)){
            $volumes = $this->book->volumes;
            krsort($volumes);
            $this->book->volumes = $volumes;
        }

        $this->assign([
            'submenu'   => $this->submenu,
            'book'      => $this->book,
            'data'      => $chapter
        ]);
        return $this->fetch();
    }

    /**
     * 章节删除
     * @access public
     * @return void
     */
    public function del($id = 0){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少章节参数id');
        }
        $chapter = ChapterModel::get($id);
        if(!$chapter){
            $this->error('章节不存在');
        }
        $chapter->together('chapter_data')->delete();
        $this->success('章节删除成功', url('index', ['book_id' => $this->book->id]));
    }
}